package com.lishu.carsafe.activity;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;
import com.lishu.carsafe.R;
import com.lishu.carsafe.adapter.ScheduleAdapter;
import com.lishu.carsafe.http.HttpBase;
import com.lishu.carsafe.http.HttpLoader;
import com.lishu.carsafe.model.BaseModel;
import com.lishu.carsafe.model.ScheduleListModel;
import com.lishu.carsafe.model.entity.Schedule;
import com.lishu.carsafe.utils.AppDialogUtils;
import com.lishu.carsafe.utils.ToastUtil;
import com.lishu.carsafe.widget.AutoVerticalScrollTextView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ScheduleActivity extends BaseActivity implements
        CalendarView.OnCalendarSelectListener,
        CalendarView.OnYearChangeListener,
        CalendarView.OnViewChangeListener,
        View.OnClickListener {

    public static final int CODE_SIGN_IN_DETAILS = 10;//签到详情使用
    public static final int CODE_SIGN_IN = 11;      //签到界面使用

    private CalendarView mCalendarView;
    private CalendarLayout mCalendarLayout;
    private AutoVerticalScrollTextView tv_schedule_date;
    private ImageView iv_schedule_up;
    private RecyclerView rv_view;
    private ScheduleAdapter adapter;
    private int myYear, myMonth, myDay;
    private ScheduleListModel listModel;

    private int clickYear,clickMonth,clickDay;//点击后的年月日

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedule);

        initView();
        initData();
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //获取数据
        analysisSchedule();
    }

    private void initData() {
        myYear = mCalendarView.getCurYear();
        myMonth = mCalendarView.getCurMonth();
        myDay = mCalendarView.getCurDay();

        clickYear = myYear;
        clickMonth = myMonth;
        clickDay = myDay;
        //更新数据
        refresh();
    }

    private void initView() {
        setTopTitle(R.string.module_schedule);
        setTopRight("今日");
        iv_schedule_up = findViewById(R.id.iv_schedule_up);
        tv_schedule_date = findViewById(R.id.tv_schedule_date);
        mCalendarView = findViewById(R.id.calendarView);
        rv_view = findViewById(R.id.rv_view);
        mCalendarLayout = findViewById(R.id.calendarLayout);

        tv_schedule_date.setText(mCalendarView.getCurYear() + "年" + mCalendarView.getCurMonth() + "月");
        // 设置布局
        rv_view.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ScheduleAdapter(this);
        rv_view.setAdapter(adapter);
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        int week = calendar.get(java.util.Calendar.DAY_OF_WEEK) - 1;//返回的是1-7
        int month = calendar.get(java.util.Calendar.MONTH) + 1;
        int day = calendar.get(java.util.Calendar.DATE);
        String dateTime = month + "-" + day + " " + getWeek(week);
        adapter.setDate(dateTime);
    }

    private void initEvent() {
        mCalendarView.setOnCalendarSelectListener(this);
        mCalendarView.setOnYearChangeListener(this);
        mCalendarView.setOnViewChangeListener(this);
        iv_schedule_up.setOnClickListener(this);
        findViewById(R.id.tv_schedule_up).setOnClickListener(this);
        findViewById(R.id.tv_schedule_down).setOnClickListener(this);
    }

    /**
     * 动态改变view的高度动画效果，动画时长300毫秒[android属性动画默认时长]
     * 原理:动画改变view LayoutParams.height的值
     *
     * @param view        要进行高度改变动画的view
     * @param startHeight 动画前的view的高度
     * @param endHeight   动画后的view的高度
     */
    public static void changeViewHeightAnimatorStart(final View view, final int startHeight, final int endHeight) {
        if (view != null && startHeight >= 0 && endHeight >= 0) {
            ValueAnimator animator = ValueAnimator.ofInt(startHeight, endHeight);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    ViewGroup.LayoutParams params = view.getLayoutParams();
                    params.height = (int) animation.getAnimatedValue();
                    view.setLayoutParams(params);
                }
            });
            animator.start();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_schedule_up:
                if (mCalendarLayout.isExpand()) {
                    mCalendarLayout.shrink();
                    iv_schedule_up.setImageResource(R.mipmap.calendar_down);
                } else {
                    mCalendarLayout.expand();
                    iv_schedule_up.setImageResource(R.mipmap.calendar_top);
                }
                break;
            case R.id.tv_schedule_up:
                mCalendarView.scrollToPre();
                break;
            case R.id.tv_schedule_down:
                mCalendarView.scrollToNext();
                break;
        }
    }

    @Override
    public void onCalendarOutOfRange(com.haibin.calendarview.Calendar calendar) {

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onCalendarSelect(com.haibin.calendarview.Calendar calendar, boolean isClick) {
        if (!isClick) {
            tv_schedule_date.setText(calendar.getYear() + "年" + calendar.getMonth() + "月");
        }
        if (myYear == calendar.getYear() && myMonth == calendar.getMonth() && calendar.getDay() == myDay) {
            setTopRight("今日");
        } else {
            setTopRight(calendar.getDay() + "日");
        }
        clickYear = calendar.getYear();
        clickMonth = calendar.getMonth();
        clickDay = calendar.getDay();
//        if (isClick) {
        //当点击后
        String dateTime = calendar.getMonth() + "-" + calendar.getDay() + " " + getWeek(calendar.getWeek());
        adapter.setDate(dateTime);
        List<Schedule> list = null;
        //如果是当月的
        if (myYear == calendar.getYear() && myMonth == calendar.getMonth()) {
            //开始遍历数据 去匹配
            int day = calendar.getDay();
            for (int i = 0; i < listModel.getData().size(); i++) {
                if (day == listModel.getData().get(i).getDay()) {
                    list = listModel.getData().get(i).getSchedules();
                    break;
                }
            }
        }
        adapter.setData(list);
    }

    @Override
    public void onYearChange(int year) {

    }

    @Override
    public void onViewChange(boolean isMonthView) {
        if (isMonthView) {
            iv_schedule_up.setImageResource(R.mipmap.calendar_top);
        } else {
            iv_schedule_up.setImageResource(R.mipmap.calendar_down);
        }
    }

    private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        return calendar;
    }

    /**
     * 请假弹窗
     */
    public void showLeave(final int id) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_schedule, null, false);
        AppDialogUtils.showLeaveDialog(this, view, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //做请假的网络请求 请求成功后更新adapter
                String content = (String) v.getTag();
                showAlways("正在请假，请稍等");
                HttpLoader.scheduleLeave(id + "", content, new HttpBase.IResponseListener() {
                    @Override
                    public void onResponse(BaseModel model) {
                        hide();
                        if (model == null) {
                            ToastUtil.showShort(R.string.please_check_network);
                            return;
                        }
                        if (!model.success()) {
                            ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                            return;
                        }
                        if(model.success()){
                            //刷新界面
                            analysisSchedule();
                        }
                    }
                });
            }
        });
    }

    /**
     * 跳转到签到界面
     *
     * @param isDetails true:签到详情界面
     */
    public void signInActivity(boolean isDetails, int id) {
        Intent intent = new Intent(this, SignInActivity.class);
        intent.putExtra(SignInActivity.IS_DETAIL, isDetails);
        intent.putExtra(SignInActivity.SCHEDULE_ID, id);
        if (isDetails) {
            startActivityForResult(intent, CODE_SIGN_IN_DETAILS);
        } else {
            startActivityForResult(intent, CODE_SIGN_IN);
        }
    }

    /**
     * 查看地图
     *
     * @param lineId 线路id
     */
    public void bdMapActivity(int lineId,String lineName) {
        Intent intent = new Intent(this, BDMapActivity.class);
        intent.putExtra(BDMapActivity.LINE_ID, lineId);
        intent.putExtra(BDMapActivity.LINE_NAME,lineName);
        startActivity(intent);
    }

    /**
     * 取消请假
     */
    public void cancelLeave(final int id) {
        showAlways("正在取消请假，请稍等");
        HttpLoader.scheduleCancelLeave(id + "", new HttpBase.IResponseListener() {
            @Override
            public void onResponse(BaseModel model) {
                hide();
                if (model == null) {
                    ToastUtil.showShort(R.string.please_check_network);
                    return;
                }
                if (!model.success()) {
                    ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                    return;
                }

                if (model.success()) {
                    //取消请假后刷新界面
                    analysisSchedule();
                }
            }
        });
    }

    /**
     * 查看排版信息
     */
    private void analysisSchedule() {
        showAlways("正在加载数据，请稍等");
        HttpLoader.getScheduleList(mCalendarView.getCurYear() + "-0" + mCalendarView.getCurMonth(), new HttpBase.IResponseListener() {
            @Override
            public void onResponse(BaseModel model) {
                hide();
                if (model == null) {
                    ToastUtil.showShort(R.string.please_check_network);
                    return;
                }
                if (!model.success()) {
                    ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                    return;
                }
                listModel = (ScheduleListModel) model;
                //更新数据
                refresh();
            }
        });
    }

    /**
     * 刷新数据
     */
    private void refresh() {
        if (listModel != null && listModel.getData() != null && listModel.getData().size() > 0) {
            Map<String, Calendar> map = new HashMap<>();
            for (int i = 0; i < listModel.getData().size(); i++) {
                int sDay = listModel.getData().get(i).getDay();
                int state = listModel.getData().get(i).getState();
                //state 0未排班 1已排班 2请假
                if (state == 1) {
                    map.put(getSchemeCalendar(myYear, myMonth, sDay, 0xFF00ADB5, "假").toString(),
                            getSchemeCalendar(myYear, myMonth, sDay, 0xFF00ADB5, "假"));//0xFFEB6767
                } else if (state == 2) {
                    map.put(getSchemeCalendar(myYear, myMonth, sDay, 0xFF00ADB5, "真").toString(),
                            getSchemeCalendar(myYear, myMonth, sDay, 0xFF00ADB5, "真"));//0xFF00ADB5
                }
            }
            //此方法在巨大的数据量上不影响遍历性能，推荐使用
            mCalendarView.setSchemeDate(map);

            List<Schedule> list = null;

            //开始遍历数据 去匹配
            for (int i = 0; i < listModel.getData().size(); i++) {
                if (clickDay == listModel.getData().get(i).getDay()) {
                    list = listModel.getData().get(i).getSchedules();
                    break;
                }
            }

            adapter.setData(list);
        }
    }

    private String getWeek(int week) {
        switch (week) {
            case 1:
                return "周一";
            case 2:
                return "周二";
            case 3:
                return "周三";
            case 4:
                return "周四";
            case 5:
                return "周五";
            case 6:
                return "周六";
            default:
                return "周日";
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_SIGN_IN:
                    //签到界面提交成功后返回
                    analysisSchedule();
                    break;
            }
        }
    }

    //模拟数据
    String json =
            "{\n" +
                    "\t\"code\": 0,\n" +
                    "\t\"msg\": \"success\",\n" +
                    "\t\"data\": [{\n" +
                    "\t\t\"day\": 1,\n" +
                    "\t\t\"state\": 0,\n" +
                    "\t\t\"schedules\": [{\n" +
                    "\t\t\t\"id \": 1,\n" +
                    "\t\t\t\"vehicle\": {\n" +
                    "\t\t\t\t\"number\": \"V001\",\n" +
                    "\t\t\t\t\"name\": \"1号车\"\n" +
                    "\t\t\t},\n" +
                    "\t\t\t\"line\": {\n" +
                    "\t\t\t\t\"id\": 2,\n" +
                    "\t\t\t\t\"name\": \"悠湖1号线\"\n" +
                    "\t\t\t},\n" +
                    "\t\t\t\"type\": 0,\n" +
                    "\t\t\t\"startTime\": \"9:00\",\n" +
                    "\t\t\t\"endTime\": \"10:00\",\n" +
                    "\t\t\t\"state\": 1,\n" +
                    "\t\t\t\"shifts\": [{\n" +
                    "\t\t\t\t\t\"sort\": 1,\n" +
                    "\t\t\t\t\t\"shiftTime\": \"9:00\",\n" +
                    "\t\t\t\t\t\"remark\": \"首班\"\n" +
                    "\t\t\t\t},\n" +
                    "\t\t\t\t{\n" +
                    "\t\t\t\t\t\"sort\": 2,\n" +
                    "\t\t\t\t\t\"shiftTime\": \"10:00\",\n" +
                    "\t\t\t\t\t\"remark\": \"末班\"\n" +
                    "\t\t\t\t}\n" +
                    "\t\t\t]\n" +
                    "\t\t}, {\n" +
                    "\t\t\t\"id \": 1,\n" +
                    "\t\t\t\"vehicle\": {\n" +
                    "\t\t\t\t\"number\": \"V001\",\n" +
                    "\t\t\t\t\"name\": \"1号车\"\n" +
                    "\t\t\t},\n" +
                    "\t\t\t\"line\": {\n" +
                    "\t\t\t\t\"id\": 2,\n" +
                    "\t\t\t\t\"name\": \"悠湖1号线\"\n" +
                    "\t\t\t},\n" +
                    "\t\t\t\"type\": 0,\n" +
                    "\t\t\t\"startTime\": \"9:00\",\n" +
                    "\t\t\t\"endTime\": \"10:00\",\n" +
                    "\t\t\t\"state\": 1,\n" +
                    "\t\t\t\"shifts\": [{\n" +
                    "\t\t\t\t\t\"sort\": 1,\n" +
                    "\t\t\t\t\t\"shiftTime\": \"9:00\",\n" +
                    "\t\t\t\t\t\"remark\": \"首班\"\n" +
                    "\t\t\t\t},\n" +
                    "\t\t\t\t{\n" +
                    "\t\t\t\t\t\"sort\": 2,\n" +
                    "\t\t\t\t\t\"shiftTime\": \"10:00\",\n" +
                    "\t\t\t\t\t\"remark\": \"末班\"\n" +
                    "\t\t\t\t}\n" +
                    "\t\t\t]\n" +
                    "\t\t}]\n" +
                    "\t}, {\n" +
                    "\t\t\"day\": 2,\n" +
                    "\t\t\"state\": 1,\n" +
                    "\t\t\"schedules\": [{\n" +
                    "\t\t\t\"id \": 2,\n" +
                    "\t\t\t\"vehicle\": {\n" +
                    "\t\t\t\t\"number\": \"V002\",\n" +
                    "\t\t\t\t\"name\": \"2号车\"\n" +
                    "\t\t\t},\n" +
                    "\t\t\t\"line\": {\n" +
                    "\t\t\t\t\"id\": 2,\n" +
                    "\t\t\t\t\"name\": \"悠湖2号线\"\n" +
                    "\t\t\t},\n" +
                    "\t\t\t\"type\": 0,\n" +
                    "\t\t\t\"startTime\": \"9:00\",\n" +
                    "\t\t\t\"endTime\": \"10:00\",\n" +
                    "\t\t\t\"state\": 2,\n" +
                    "\t\t\t\"shifts\": [{\n" +
                    "\t\t\t\t\t\"sort\": 1,\n" +
                    "\t\t\t\t\t\"shiftTime\": \"9:00\",\n" +
                    "\t\t\t\t\t\"remark\": \"首班\"\n" +
                    "\t\t\t\t},\n" +
                    "\t\t\t\t{\n" +
                    "\t\t\t\t\t\"sort\": 2,\n" +
                    "\t\t\t\t\t\"shiftTime\": \"10:00\",\n" +
                    "\t\t\t\t\t\"remark\": \"末班\"\n" +
                    "\t\t\t\t}\n" +
                    "\t\t\t]\n" +
                    "\t\t}]\n" +
                    "\t}]\n" +
                    "}";
}
